<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\cdc;

use app\enum\CdcEnum;
use app\model\mongo\MongoStatModel;
use app\model\mongo\MongoSyncModel;
use app\service\BaseService;

final class AccountService extends BaseService
{
    /**
     * 添加统计数据.
     * @param MongoStatModel $model 统计数据模型
     * @param array $fields 保存字段
     */
    public static function addStat(MongoStatModel $model, array $fields = []): bool
    {
        $model->setAttrs($fields);
        return $model->save();
    }

    /**
     * 获取统计数据模型.
     * @param int $mediaId 媒体ID
     * @param int $type 统计类型
     * @param array $where 查询条件
     * @return bool|mixed
     */
    public static function getStatModel(int $mediaId = 0, int $type = 0, array $where = [])
    {
        $className = CdcEnum::getClassNames($mediaId, 'account_stat', $type);
        if (! $className) {
            return self::setError('获取统计数据模型失败');
        }

        $model = new $className();
        if ($where) {
            return $model->where($where)->findOrEmpty();
        }
        return $model;
    }

    /**
     * 删除中间表数据.
     * @param MongoSyncModel $model 中间表模型
     * @param int $type 类型
     */
    public static function deleteSyncLog(MongoSyncModel $model, int $type = 0): bool
    {
        if ($type == 0) {
            $where = ['_id' => $model->getKey()];
        } elseif ($type == 1) {
            $where = [
                'account_id' => $model->getAttr('account_id'),
                'video_id' => $model->getAttr('video_id'),
                'stat_date' => ['$lte', $model->getAttr('stat_date')],
            ];

            if ($model->getAttr('type')) {
                $where['type'] = $model->getAttr('type');
            }
        } else {
            return self::setError('未知的删除类型');
        }

        $res = $model->where($where)->delete();

        if ($res <= 0) {
            return false;
        }

        return true;
    }

    /**
     * 添加中间表.
     * @param MongoSyncModel $model 中间表模型
     * @param array $fields 字段数组
     */
    public static function addSyncLog(MongoSyncModel $model, array $fields = []): bool
    {
        $model->setAttrs($fields);
        $model->setAttr('create_time', time());
        $model->setAttr('update_time', time());
        return $model->save();
    }
}
